import "./index.css"; // 防跳功能
import {
  NavLink,
  Route,
  useHistory,
  Switch,
  Redirect,
  useLocation,
} from "react-router-dom";
import axios from "./service/index";
import React, { useState, useEffect } from "react";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import * as allIcons from "@ant-design/icons";
import { Layout, Menu, theme, message, Modal } from "antd";

import Welcome from "./views/Welcome";
import User from "./views/User";
import Film from "./views/Film";
import Cinema from "./views/Cinema";
import College from "./views/College";
import Icon from "./icon";

const { Header, Sider, Content } = Layout;

export default function App() {
  let history = useHistory();
  let location = useLocation();
  let [isLogin, setLogin] = useState(false); // isLogin 登录的状态
  let [items, setItems] = useState([]);
  let navMenus = JSON.parse(localStorage.getItem("acl"));
  let [userInfo, setUserInfo] = useState({});
  // let [icon, setIcon] = useState("");
  // 写法1：
  // const getItem = (label, key, icon, children) => {
  //   return {
  //     key, // 菜单项的key，唯一值
  //     icon, // icon图标
  //     children, // 子菜单项目
  //     label, // 菜单项的内容
  //   };
  // };
  // 动态生成菜单项
  let tempArr = [];
  if (navMenus) {
    // 方法1：
    // navMenus.forEach((item) => {
    //   if (item.children.length > 0) {
    //     // 有子菜单
    //     tempArr.push(
    //       getItem(
    //         item.auth_name,
    //         item.auth_path,
    //         <UserOutlined />,
    //         item.children.map((subItem) => {
    //           if (subItem.is_nav === 1) {
    //             // 要渲染的导航菜单项目
    //             return getItem(
    //               <NavLink to={subItem.auth_path}>{subItem.auth_name}</NavLink>,
    //               subItem.auth_path
    //             );
    //           }
    //         })
    //       )
    //     );
    //   } else {
    //     // 无子菜单
    //     tempArr.push(
    //       getItem(
    //         <NavLink to={item.auth_path}>{item.auth_name}</NavLink>,
    //         item.auth_path
    //       )
    //     );
    //   }
    // });

    // 方法2;
    tempArr = navMenus.map((item) => {
      // console.log(item);

      // let newStr = JSON.parse(JSON.stringify(item.nav_icon));
      if (item.children.length === 0) {
        // 没有子菜单的
        // let newIcon = JSON.parse(JSON.stringify(icon))
        // console.log(newStr);
        return {
          key: item.id,
          label: <NavLink to={item.auth_path}>{item.auth_name}</NavLink>,
          // icon: React.createElement(allIcons['BankOutlined']),
          icon: <Icon icon={"BankOutlined"} />,
        };
      } else {
        // 有子菜单的
        return {
          key: item.id,
          label: item.auth_name,
          icon: React.createElement(allIcons["AppstoreAddOutlined"]),
          children: item.children.map((subItem) => {
            if (subItem.is_nav === 1) {
              return {
                key: subItem.id,
                label: (
                  <NavLink to={subItem.auth_path}>{subItem.auth_name}</NavLink>
                ),
              };
            }
          }),
        };
      }
    });
  }
  // 是否已经登录成功  防跳
  useEffect(() => {
    axios.get("/api/common/auth/jwtPreCheck").then((res) => {
      if (res.errNo === 0) {
        message.info(res.message, 1);
        setLogin(true); // 登录成功之后，设置登录的状态为 true
        setItems([...tempArr]); // 侧边栏数据
        // 获取管理员信息
        axios.get("api/common/auth/adminInfo").then((res) => {
          // console.log(res);
          if (res.errNo === 0) {
            // 说明登录成功
            setUserInfo({ ...res.accountInfo });
          }
        });
      } else {
        message.error(res.errText);
        history.push("/login"); // 没有登录需要跳转到登录页面
      }
    });
  }, []);

  // 控制导航条的展开折叠
  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer },
  } = theme.useToken();
  // 点击 注销登录
  const quit = () => {
    Modal.confirm({
      title: "提示",
      icon: <ExclamationCircleOutlined />,
      content: "你要注销登录吗？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        localStorage.removeItem("jwt");
        localStorage.removeItem("acl");
        history.push("/login");
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  return (
    <>
      {isLogin && (
        <Layout style={{ height: "100%" }}>
          <Sider
            trigger={null}
            collapsible
            collapsed={collapsed}
            style={{ height: "100%" }}
          >
            <div className="logo">
              <img src='https://img2.baidu.com/it/u=1484874357,836462174&fm=253&fmt=auto&app=138&f=PNG?w=220&h=220' ></img>
              <span>影视后台管理系统</span>
            </div>
            <Menu
              theme="dark"
              mode="inline"
              defaultSelectedKeys={[location.pathname]}
              items={items}
            />
          </Sider>

          <Layout className="site-layout">
            <Header
              style={{
                padding: "0px 10px",
                background: colorBgContainer,
              }}
            >
              {location.pathname}
              {React.createElement(
                collapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
                {
                  className: "trigger",
                  onClick: () => setCollapsed(!collapsed),
                }
              )}
              {/* {
                collapsed?<MenuUnfoldOutlined onClick={ () => setCollapsed(!collapsed)} />:<MenuFoldOutlined onClick={ () => setCollapsed(!collapsed)}  />
              } */}
              <span style={{ paddingLeft: "20px" }}>
                {userInfo.username + "/" + userInfo.role}
              </span>

              <span
                style={{ float: "right", padding: "0px 30px", color: "blue" }}
                onClick={quit}
              >
                注销登录
              </span>
            </Header>
            <Content
              style={{
                margin: "24px 16px",
                padding: 24,
                minHeight: 280,
                background: colorBgContainer,
              }}
            >
              <Switch>
                <Route path="/dashboard/welcome" component={Welcome} />
                <Route path="/dashboard/user/index" component={User} />
                <Route path="/dashboard/film/index" component={Film} />
                <Route path="/dashboard/cinema/index" component={Cinema} />
                <Route path="/dashboard/college/index" component={College} />
                <Redirect from="/dashboard" to="/dashboard/welcome" exact />
              </Switch>
            </Content>
          </Layout>
        </Layout>
      )}
    </>
  );
}
